<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '数据上传',
    navigationBarBackgroundColor: '#1989fa',
    navigationBarTextStyle: 'white',
  },
}
</route>
<template>
  <Loyout class="update-page" bgc="#F3F8FE">
    <view class="update-page flex flex-column" style="height: 100%; overflow: hidden">
      <wd-form ref="form" :model="outFormdata">
        <wd-cell-group border>
          <wd-picker :columns="Lst_order_type" label="单据类型" v-model="outFormdata.order_type" />
          <wd-picker :columns="Lst_order_status" label="导出状态" v-model="outFormdata.status" />
        </wd-cell-group>
      </wd-form>
      <scroll-view class="flex1 pt-20" scroll-y>
        <wd-card v-for="item in outList" :key="item.out_order_no">
          <template #title>
            <view class="flex-row pt-20">
              <wd-icon color="#0083ff" size="16" name="list" class="pr-6" />
              <view class="fs-28 titleCode">
                {{ item.out_order_no }}
              </view>
            </view>
          </template>
          <view class="flex1 flex-row">
            <view class="flex1 flex-row flex-align-center">
              <view>
                <view class="flex-col">
                  <view class="fs-24">往来机构：{{ item.org_code }}</view>
                  <view class="fs-24">商品数量：{{ item.count }}</view>
                </view>
              </view>
            </view>
            <view class="flex-align-center">
              <wd-checkbox v-model="item.checked" shape="square"></wd-checkbox>
            </view>
          </view>
        </wd-card>
      </scroll-view>
    </view>
    <template #footer>
      <wd-button
        class="flex1"
        size="large"
        @click="checkedAll(outList.filter((v) => v.checked).length)"
      >
        {{ outList.filter((v) => v.checked).length === outList.length ? '全不选' : '全选' }}
      </wd-button>
      <wd-button class="flex1 ml-20" size="large" @click="startUpload">开始上传</wd-button>
      <wd-button class="flex1 ml-20" size="large" @click="deleteHandle">删 除</wd-button>
    </template>
  </Loyout>
</template>

<script lang="ts" setup>
import Loyout from '@/layouts/index.vue'
import { useOrderConfigStore } from '@/store/orderconfig'
import { GoodsType, OrderType, Lst_order_type, OutOrderStatus, Lst_order_status } from '@/enum'
import OutSqlLite, { OutorderTable } from '@/utils/out-sqlite'
import OutGoodsSqlLite, { OutorderGoodsTable } from '@/utils/out-goods-sqlite'
import { useSocket } from '@/utils/socket'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/user'
import { useToast } from 'wot-design-uni'

const Toast = useToast()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const orderConfigStore = useOrderConfigStore()

const outFormdata = reactive<OutorderTable>({
  out_order_no: '',
  org_code: '',
  goods_type: GoodsType.NORMAL,
  order_type: OrderType.OUT,
  create_at: '',
  status: OutOrderStatus.UNEXPORT,
  delete_flag: '0',
})

const outList = ref([])
onLoad(() => fetchData())

const fetchData = async () => {
  await getOutList()
  await getOutGoodsCounts()
}

const checkedAll = (length) => {
  if (length === outList.value.length || length === 0) {
    outList.value.forEach((v) => {
      v.checked = length !== outList.value.length
    })
  }
}

const getOutList = async () => {
  const data = await OutSqlLite.search(
    {
      status: outFormdata.status,
      order_type: outFormdata.order_type,
      delete_flag: outFormdata.delete_flag,
    },
    { pageSize: 100, pageNum: 1 },
  )
  outList.value = data
  return Promise.resolve(data)
}

const getOutGoodsCounts = async () => {
  outList.value.forEach(async (item) => {
    item.checked = false
    const count = await OutGoodsSqlLite.countSql({
      out_order_no: item.out_order_no,
      delete_flag: outFormdata.delete_flag,
    })
    item.count = count
    const goodsList = await OutGoodsSqlLite.search(
      {
        out_order_no: item.out_order_no,
        delete_flag: '0',
      },
      { pageSize: count, pageNum: 1 },
    )
    item.goodsList = goodsList
  })
  return Promise.resolve(true)
}

const startUpload = async () => {
  const list = outList.value.filter((v) => v.checked)
  if (!list.length) return Toast.error('请选择单据')
  try {
    const socket = await useSocket({
      type: 'UploadOutFile',
      callback: (res) => {
        console.log('UploadOutFile', res)
        uploadDone(outList.value)
        Toast.success('上传成功')
        fetchData()
      },
    })
    console.log('socket', socket)
    const xml = createdXmlStr2(list)
    console.log('xml', xml)
    uni.sendSocketMessage({
      data: JSON.stringify(xml),
      complete: (complete) => {
        console.log('complete', complete)
      },
      fail: (fail) => {
        console.log('fail', fail)
      },
    })
  } catch (error) {
    console.log('error', error)
  }
}

const createdXmlStr2 = (list) => {
  const xmlStrs = list.map((v) => {
    return `<?xml version="1.0" encoding="utf-8"?>
      <Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="终端接口XML Schema-3.0.xsd" SN="BZ010" Version="3.0" License="1001122">
          <Events>
    <Event Name="SalesWareHouseOut" MainAction="WareHouseOut">
                <ActionMaping>
                    <Action Name="WareHouseOut">
                      <ActionData>CorpOrderID</ActionData>
                      <ActionData>Actor</ActionData>
                      <ActionData>ToCorpID</ActionData>
                      <ActionData>ActDate</ActionData>
                      <ActionData>Code</ActionData>
                    </Action>
                </ActionMaping>
                <DataMaping>
                    <MetaData Name="${v.out_order_no}" Type="String"/>
                    <MetaData Name="${v.org_code}" Type="String"/>
                    <MetaData Name="${dayjs(v.create_at).format(
                      'YYYY-MM-DD HH:mm:ss',
                    )}" Type="Date"/>
                    <MetaData Name="${v.org_code}" Type="String"/>
                    <MetaData Name="${v.org_code}" Type="String"/>
                </DataMaping>
                <DataField>
                ${v.goodsList
                  .map((goods) => {
                    return `<Data Code="${goods.code}" CorpOrderID="${
                      v.out_order_no
                    }" Actor="admin" ActDate="${dayjs(goods.create_at).format(
                      'YYYY-MM-DD HH:mm:ss',
                    )}" ToCorpID="${v.org_code}"/>`
                  })
                  .join('')}
                </DataField>
              </Event>
              </Events>
      </Document>`
  })
  return xmlStrs
}

// 上传完成后更改单据状态 删除商品
const uploadDone = (list) => {
  console.log('uploadDone')
  list.forEach(async (item) => {
    await OutSqlLite.updata({ out_order_no: item.out_order_no }, { status: OutOrderStatus.EXPORT })
    await OutGoodsSqlLite.delete(item.goodsList)
  })
}

const deleteHandle = async () => {
  const list = outList.value.filter((v) => v.checked)
  if (!list.length) return Toast.error('请选择单据')
  const goods = []
  list.forEach((v) => {
    if (v?.goodsList.length) {
      goods.push(...v.goodsList)
    }
  })
  await OutSqlLite.delete(
    list.map((v) => {
      const obj = Object.assign({}, v)
      delete obj.goodsList
      return obj
    }),
  )
  await OutGoodsSqlLite.delete(goods)
  Toast.success('删除成功')
  fetchData()
}
</script>

<style lang="scss">
.update-page {
  .wd-card__title-content {
    padding: 0 !important;
  }
  .titleCode {
    color: black;
  }
}
</style>
